/*
 *    Copyright 2022 CManLH
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.lifeonwalden.ms.async.runner.thread;

import com.lifeonwalden.ms.async.runner.bean.AsyncRunnerItem;
import com.lifeonwalden.ms.async.runner.service.RunnerService;
import com.lifeonwalden.ms.common.logger.LoggerUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Dispatcher implements Runnable {
    private final static Logger logger = LoggerUtil.getLogger(Dispatcher.class);

    private int maxRunner;

    private int maxIdelRunner;

    // 轮询间隔时间, 分钟计
    private int poolingInterval;

    public final static AsyncRunnerItem EMPTY = new AsyncRunnerItem(new Object(), -1);

    private ConcurrentHashMap<Integer, RunnerService> runner;

    private BlockingQueue<AsyncRunnerItem> queue;

    private BlockingQueue<AsyncRunnerItem> secondLevelQueue;

    private AtomicInteger runnerCounter = new AtomicInteger(0);

    public Dispatcher(int maxThread, int maxIdelThread, int poolingInterval, int secondLevelQueueSize, BlockingQueue<AsyncRunnerItem> queue, ConcurrentHashMap<Integer, RunnerService> runner) {
        this.maxRunner = maxThread;
        this.maxIdelRunner = maxIdelThread;
        this.poolingInterval = poolingInterval;
        this.queue = queue;
        this.runner = runner;
        this.secondLevelQueue = new ArrayBlockingQueue<>(secondLevelQueueSize);

        newRunner();
    }

    @Override
    public void run() {
        while (true) {
            try {
                AsyncRunnerItem item = queue.poll(poolingInterval, TimeUnit.MINUTES);
                if (null != item) {
                    secondLevelQueue.put(item);
                    if (queue.size() > 1) {
                        newRunner();
                    }
                } else {
                    if (secondLevelQueue.size() < maxIdelRunner) {
                        secondLevelQueue.put(EMPTY);
                    }
                }

                if (secondLevelQueue.size() > 1.5 * maxIdelRunner) {
                    newRunner();
                }
            } catch (InterruptedException e) {
                logger.error("Dispatcher interrupted", e);
            }
        }
    }

    private void newRunner() {
        if (runnerCounter.get() >= maxRunner) {
            logger.warn("Too much work to do, need add more runner.");

            return;
        }

        if (runnerCounter.incrementAndGet() <= maxRunner) {
            new Thread(new com.lifeonwalden.ms.async.runner.thread.Runner(this.runner, this.secondLevelQueue, this.runnerCounter), "AsyncRunner_".concat(StringUtils.leftPad(String.valueOf(runnerCounter.get()), 3, '0')).concat("_").concat(String.valueOf(System.currentTimeMillis()))).start();

            logger.warn("{} runner is working.", runnerCounter.get());
        } else {
            runnerCounter.decrementAndGet();
        }
    }
}
